
Imports System
Imports System.Collections

Namespace _2bMatesSite.BO
	''' <summary>
	''' Base class for a list of user' objects
	''' </summary>
	Public MustInherit Class BaseList
		Inherits RandomizedList
		Protected list As HashArray

		Public Sub Refresh()
			' Re-init
			list.SetList(LoadList())
		End Sub

		Public Sub Add(ByVal value As Object)
			If AddItem(value) AndAlso list <> Nothing Then
				list.Add(value)
			End If
		End Sub

		Public ReadOnly Property Values() As ICollection
			Get
				Return LoadListOnDemand().Values
			End Get
		End Property

		Public Function Contains(ByVal itemID As Integer) As Boolean
			Return LoadListOnDemand().ContainsKey(itemID)
		End Function

		Public Function Contains(ByVal value As Object) As Boolean
			Return LoadListOnDemand().ContainsValue(value)
		End Function

		Public Sub Clear()
			ClearList()
			list = Nothing
		End Sub

		Public Sub Remove(ByVal itemID As Integer)
			If list <> Nothing Then
				list.Remove(itemID)
			End If
			DeleteItem(itemID)
		End Sub

		Public Sub Remove(ByVal value As Object)
			Remove(value.GetHashCode())
		End Sub

		Public ReadOnly Property Count() As Integer
			Get
				Return LoadListOnDemand().Count
			End Get
		End Property

		Public Function GetEnumerator() As IEnumerator
			Return LoadListOnDemand().Values.GetEnumerator()
		End Function


		Protected Function LoadListOnDemand() As Hashtable
			If list = Nothing Then
				list = New HashArray(LoadList())
			End If

			Return list.hash
		End Function

		Public Overloads Overrides Function GetList() As IList
			LoadListOnDemand()
			Return list.array
		End Function

		Protected MustOverride Function LoadList() As Hashtable
		Protected MustOverride Sub ClearList()

		Protected MustOverride Sub DeleteItem(ByVal itemID As Integer)
		Protected MustOverride Sub DeleteItem(ByVal item As Object)

		Protected MustOverride Function AddItem(ByVal item As Object) As Boolean

		'
		' Internal classes
		'

		Protected Class HashArray
			Public array As ArrayList
			Public hash As Hashtable

			Public Sub New(ByVal list As Hashtable)
				SetList(list)
			End Sub

			Public Sub SetList(ByVal list As Hashtable)
				If list <> Nothing Then
					array = New ArrayList(list.Values)
				Else
					array = Nothing
				End If

				hash = list
			End Sub

			Public Sub Add(ByVal obj As Object)
				array.Add(obj)
				hash.Add(obj.GetHashCode(), obj)
			End Sub

			Public Sub Remove(ByVal itemID As Integer)
				array.Remove(hash(itemID))
				hash.Remove(itemID)
			End Sub
		End Class
	End Class
End Namespace






